package com.bootdo.system.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONObject;  

public class WeixinUtil {
	static String  url="https://api.weixin.qq.com/sns/jscode2session";
	public static JSONObject getSessionKey(String appid, String jsCode, String secret) {
		Map<String,String> param = new HashMap<String,String>();
		param.put("appid", appid);
		param.put("secret", secret);
		param.put("js_code", jsCode);
		param.put("grant_type", "authorization_code");
		System.out.println("appid="+appid+",jscode==" + jsCode + ",secret=" + secret);
		String result = doPost(url,param,"UTF-8");
		JSONObject json = JSONObject.parseObject(result);
		return json;
	}
	
	public static String doPost(String url,Map<String,String> map,String charset){  
        HttpClient httpClient = null;  
        HttpPost httpPost = null;  
        String result = null;  
        try{  
            httpClient = new SSLClient();  
            System.out.println("httpClient is null===" + (httpClient==null));
            httpPost = new HttpPost(url);  
            System.out.println("httpPost is null===" + (httpPost==null));
            //设置参数  
            List<NameValuePair> list = new ArrayList<NameValuePair>();  
            Iterator iterator = map.entrySet().iterator();  
            while(iterator.hasNext()){  
                Entry<String,String> elem = (Entry<String, String>) iterator.next();  
                list.add(new BasicNameValuePair(elem.getKey(),elem.getValue()));  
            }  
            if(list.size() > 0){  
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,charset);  
                httpPost.setEntity(entity);  
            }  
            HttpResponse response = httpClient.execute(httpPost);  
            if(response != null){  
                HttpEntity resEntity = response.getEntity();  
                if(resEntity != null){  
                	System.out.println("charset===" + charset);
                    result = EntityUtils.toString(resEntity,charset);  
                    System.out.println("result===" + result);
                }  
            }else {
            	System.out.println("response is null ...");
            }
        }catch(Exception ex){  
            ex.printStackTrace();  
        }  
        return result;  
    } 

	public static String getRandom(int len) {
		String ret = "";
		Random r = new Random();
		for(int i=0;i<len;i++) {
			ret += r.nextInt(9);
		}
		return ret;
	}
}
